package com.hmdp;

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String[] args) {
        int port = 13001; // 服务端监听的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                try (Socket clientSocket = serverSocket.accept()) {
                    System.out.println("客户端已连接: " + clientSocket.getInetAddress());

                    // 获取输出流，向客户端发送消息
                    OutputStream outputStream = clientSocket.getOutputStream();
                    PrintWriter out = new PrintWriter(outputStream, true);
                    out.println("欢迎连接到TCP服务器！");

                    // 获取输入流，接收客户端消息
                    InputStream inputStream = clientSocket.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println("收到客户端消息: " + inputLine);
                    }
                } catch (IOException e) {
                    System.err.println("处理客户端连接时发生错误: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("无法启动服务器: " + e.getMessage());
        }
    }
}
